package com.lagou.rpc.common.entity;

import com.lagou.rpc.common.converter.Converter;

import java.util.HashMap;
import java.util.Map;

/**
 * simpleRpc协议对象构建器
 *
 * @author wlz
 * @date 2020/4/30
 */
public class SimpleRpcProtocolBuilder {

    public static final String STATUS_HEADER_KEY = "status_header_key";
    public static final String ERROR_HEADER_KEY = "error_header_key";
    public static final String DATA_HEADER_KEY = "data_header_key";
    public static final String OK_STATUS = "200";
    public static final String ERROR_STATUS = "500";

    private SimpleRpcProtocolBuilder() {

    }

    public static SimpleRpcProtocol buildErrorProtocolData(Throwable e, Converter converter) {

        SimpleRpcProtocol simpleRpcProtocol = new SimpleRpcProtocol();
        Map<String, String> header = new HashMap<>(2);
        header.put(STATUS_HEADER_KEY, ERROR_STATUS);
        header.put(ERROR_HEADER_KEY, e.getMessage());
        byte[] headerContent = converter.obj2Bytes(header);
        simpleRpcProtocol.setHeader(headerContent);
        simpleRpcProtocol.setHeaderLength((short) headerContent.length);
        simpleRpcProtocol.setLength(0);
        simpleRpcProtocol.setContent(new byte[0]);
        return simpleRpcProtocol;
    }


    public static SimpleRpcProtocol buildSuccessProtocolData(Object obj, Converter converter) {
        SimpleRpcProtocol simpleRpcProtocol = new SimpleRpcProtocol();
        Map<String, String> header = new HashMap<>(2);
        header.put(STATUS_HEADER_KEY, OK_STATUS);
        header.put(DATA_HEADER_KEY, obj.getClass().getName());
        byte[] headerContent = converter.obj2Bytes(header);
        simpleRpcProtocol.setHeader(headerContent);
        simpleRpcProtocol.setHeaderLength((short) headerContent.length);
        byte[] content = converter.obj2Bytes(obj);
        simpleRpcProtocol.setLength(content.length);
        simpleRpcProtocol.setContent(content);
        return simpleRpcProtocol;
    }


}
